<?php

/**
 * 订单逻辑封装
 */

namespace Logic;

class Order {

    private $id = 0;
    private $order_id = '';
    private $user_id = '';

    public function __construct($id = 0, $user_id = '', $order_id = '') {
        $this->id = $id;
        $this->user_id = $user_id;
        $this->order_id = $order_id;
    }

    /**
     * 订单登记
     */
    public function update() {
        // 验证数据
        $this->valid();

        // 开启事务
        if (!\Db::instance()->startTransactions()) {
            \Common::ajaxReturnFalse('订单登记, 事务开启失败');
        }

        try {
            if ($this->id && !\Db::instance()->execute("delete from `myorder` where `id`='$this->id'")) {
                throw new \Exception('订单登记, 数据清理失败');
            }

            $ret = $this->getOrderInfo();
            $param = [
                'user_id' => $this->user_id,
                'order_id' => $this->order_id,
                'status' => $ret['status'] == 2 ? 0 : $ret['status'],
                'total_packet' => $ret['total_packet'],
            ];

            if (\Db::instance()->count("select count(1) from `myorder` where `order_id`='$this->order_id'")) {
                $ret = \Db::instance()->updateByWhere('myorder', $param, "`order_id`='$this->order_id'");
            } else {
                $ret = \Db::instance()->insert('myorder', $param);
            }

            if (!$ret) {
                throw new \Exception('订单登记失败, 请稍后重试');
            }

            $tb_uid = substr($this->order_id, -6);
            if (!\Db::instance()->count("select count(1) from `relation_user` where `tb_uid`='$tb_uid'")) {
                $ret = \Db::instance()->insert('relation_user', ['user_id' => $this->user_id, 'tb_uid' => $tb_uid]);
                if (!$ret) {
                    throw new Exception('订单登记, 账号关联失败');
                }
            }


            if (!\Db::instance()->commit()) {
                throw new Exception('订单登记, 提交事务失败');
            }

            \Common::ajaxReturnSuccess('恭喜, 订单登记成功, 去‘我的订单’查看');
        } catch (\Exception $e) {
            \Db::instance()->rollback();
            \Common::ajaxReturnFalse($e->getMessage());
        }
    }

    /**
     * 发放红包
     */
    public function give() {
        $row = \Db::instance()->getRow("select `id`,`order_id`,`user_id`,`status` from `myorder` where `id`='$this->id'");
        if (!$row) {
            \Common::ajaxReturnFalse("没有找到当前记录");
        }

        if ($row['status'] != 5) {
            \Common::ajaxReturnFalse("订单未结算, 不能发放红包");
        }

        $param = [
            'status' => 6,
            'packet_time' => time(),
        ];
        $ret = \Db::instance()->updateById('myorder', $param, $this->id);
        if (!$ret) {
            \Common::ajaxReturnFalse("数据更新失败");
        } else {
            \Common::ajaxReturnSuccess("红包发放成功");
        }
    }

    /**
     * 基础的验证
     */
    private function valid() {

        // 验证用户账号信息
        if (!$this->user_id) {
            \Common::ajaxReturnFalse('登录账号异常, 请重新登录');
        }

        $row = \Db::instance()->getRow("select `user_id`,`status` from `user` where `user_id`='$this->user_id'");
        if (!$row) {
            \Common::ajaxReturnFalse("系统没有查到账户信息");
        }
        if (!$row['status']) {
            \Common::ajaxReturnFalse('账号已被禁用');
        }

        // 参数信息
        if (!$this->order_id) {
            \Common::ajaxReturnFalse("订单号不能为空");
        }

        if (!ctype_digit(strval($this->order_id))) {
            \Common::ajaxReturnFalse("录入的订单号格式有误");
        }

        // 订单号最小长度
        $min_order_length = 18;
        if (strlen($this->order_id) < $min_order_length) {
            \Common::ajaxReturnFalse("录入的订单号长度不够");
        }

        if ($this->id) {
            $row = \Db::instance()->getRow("select `status` from `myorder` where `id`='$this->id'");
            if (!$row) {
                \Common::ajaxReturnFalse("编辑的订单登记信息不存在");
            }

            if ($row['status'] != 1 && $row['status'] != 2) {
                \Common::ajaxReturnFalse("只有待审核和审核驳回的记录可以修改调整");
            }
        }

        // 查询订单号是否已录入
        $where = $this->id ? "`order_id`='$this->order_id' and `id` <> '$this->id'" : "`order_id`='$this->order_id'";
        $row = \Db::instance()->getRow("select `user_id`,`order_id` from `myorder` where $where");
        if ($row) {
            if ($row['user_id'] && $this->user_id == $row['user_id']) {
                \Common::ajaxReturnFalse("订单号{$this->order_id}已登记过, 请不要重复登记");
            }

            if ($row['user_id'] && $this->user_id != $row['user_id']) {
                \Common::ajaxReturnFalse("订单号{$this->order_id}, 已被账号{$row['user_id']}登记");
            }
        }
    }

    /**
     * 获取订单的状态
     */
    public function getOrderInfo() {
        $return = [
            'status' => 0,
            'total_packet' => 0,
        ];

        $row = \Db::instance()->getList("select `order_id`,`product_id`,`order_status`,`red_packet` from `orderlist` where `order_id`='$this->order_id'");
        if (!$row) {
            // 没有找到订单记录，状态为审核驳回
            $return['status'] = 2;
            return $return;
        }

        // 是否订单失效
        $ts = 3;
        foreach ($row as $r) {
            if ($r['order_status'] != '订单失效') {
                $ts = 5;
                break;
            }
        }
        if ($ts == 3) {
            $return['status'] = 3;
            return $return;
        }

        // 是否订单结算（订单结算）
        $ts = 5;
        $total_packet = 0;
        foreach ($row as $r) {
            if ($r['order_status'] != '订单结算' && $r['order_status'] != '订单失效') {
                $ts = 0;
                break;
            }
            $total_packet += $r['red_packet'];
        }

        if ($ts) {
            // 订单结算
            $return['status'] = 5;
            $return['total_packet'] = $total_packet;
        } else {
            // 订单付款, 等待收货结算
            $return['status'] = 4;
        }

        return $return;
    }

}
